package com.service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.stereotype.Service;

import com.dto.Document;
import com.entity.CommentEntity;
import com.entity.CommentsEntity;
import com.entity.FieldsEntity;
import com.entity.IssueEntity;
import com.entity.IssueTypeEntity;
import com.entity.PriorityEntity;
import com.entity.ProjectEntity;
import com.entity.ResolutionEntity;
import com.entity.StatusEntity;
import com.entity.SubtasksEntity;
import com.entity.UserEntity;
import com.entity.WorklogEntity;
import com.entity.WorklogsEntity;

@Service
public class ExcelReportService {
	public void createReportPoi(List<IssueEntity> ticketsList) {

		if (ticketsList.size() != 0) {

			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

			ServletContext ctx = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext());
			String filename = ctx.getRealPath("JSONFolder//outPOI.xls");

			// String filename =
			// classLoader.getResource("JSONFolder//outPOI.xls").getPath();
			Workbook wb = new HSSFWorkbook();

			Sheet s = wb.createSheet();

			Row r = null;
			Cell c = null;
			int rownum = 0;
			String cellValue;

			CellStyle style = wb.createCellStyle();
			style.setFillForegroundColor(IndexedColors.PINK.getIndex());
			style.setFillPattern(CellStyle.SOLID_FOREGROUND);

			for (IssueEntity entity : ticketsList) {
				int cellnum = 0;
				r = row(s, rownum);
				rownum = rownum + 2;

				Cell cell = r.createCell(cellnum);
				cell.setCellValue("Ticket: " + entity.getKeyIssue());
				cell.setCellStyle(style);
				cellnum++;

				cellnum = cell(r, cellnum, entity.getFieldsEntity().getSummary());

				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Reporter: " + entity.getFieldsEntity().getUserEntityByIdReporter().getName());

				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Summary: " + entity.getFieldsEntity().getSummary());
				cellnum = cell(r, cellnum, "Priority: " + entity.getFieldsEntity().getPriorityEntity().getId() + "."
						+ entity.getFieldsEntity().getPriorityEntity().getName());
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "TimeSpent: " + entity.getFieldsEntity().getTimespent());
				cellnum = cell(r, cellnum, "Status: " + entity.getFieldsEntity().getStatusEntity().getId() + "."
						+ entity.getFieldsEntity().getStatusEntity().getName());
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "IssueType: " + entity.getFieldsEntity().getIssueTypeEntity().getId() + "."
						+ entity.getFieldsEntity().getIssueTypeEntity().getName());
				cellnum = cell(r, cellnum, "Description: " + entity.getFieldsEntity().getDescription());
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				if (entity.getFieldsEntity().getIssueEntity() != null) {
					cellnum = cell(r, 1, "Parent Ticket: " + entity.getFieldsEntity().getIssueEntity().getKeyIssue());
				} else {
					cellnum = cell(r, 1, "Parent Ticket: " + "no parent ticket");
				}

				wb.getSheetAt(0).autoSizeColumn(cellnum);

				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Created: " + entity.getFieldsEntity().getCreated());
				cellnum = cell(r, cellnum, "Project: " + entity.getFieldsEntity().getProjectEntity().getName());

				r = row(s, rownum);
				rownum++;
				cellnum = 0;
				cell(r, cellnum, "Updated: " + entity.getFieldsEntity().getUpdated());

				if (entity.getFieldsEntity().getCommentEntity() != null) {

					Set<CommentsEntity> comments = entity.getFieldsEntity().getCommentEntity().getCommentsEntities();
					Row rBody = row(s, rownum);
					rownum++;
					Row rDate = row(s, rownum);
					rownum++;
					Row rAuthor = row(s, rownum);
					rownum = rownum + 2;
					cell(rBody, 0, "Comment Body: ");
					cell(rDate, 0, "Comment created Date: ");
					cell(rAuthor, 0, "Comment Author Name: ");
					cellnum = 1;
					for (CommentsEntity comment : comments) {
						cellValue = comment.getBody();
						cell(rBody, cellnum, cellValue);
						cellValue = comment.getCreated().toString();
						cell(rDate, cellnum, cellValue);
						cellValue = comment.getUserEntityByIdAuthor().getName();
						cell(rAuthor, cellnum, cellValue);
						cellnum++;
					}
					for (int colNum = 0; colNum < rBody.getLastCellNum(); colNum++) {
						wb.getSheetAt(0).autoSizeColumn(colNum);
					}
				}
				if (entity.getFieldsEntity().getResolutionEntity() != null) {
					r = row(s, rownum);
					rownum = rownum + 2;
					cellnum = 0;
					cellnum = cell(r, cellnum, "Resolution: " + entity.getFieldsEntity().getResolutionEntity().getName());
					cellnum = cell(r, cellnum, "Resolution Date: " + entity.getFieldsEntity().getResolutionDate());

					cellnum = cell(r, cellnum, "Descriprion: " + entity.getFieldsEntity().getResolutionEntity().getDescription());
				} else {
					r = row(s, rownum);
					rownum = rownum + 2;
					cellnum = 0;
					cellnum = cell(r, cellnum, "Resolution: no resolution yet");
				}
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Due date: " + entity.getFieldsEntity().getDuedate());

				if (entity.getFieldsEntity().getWorklogEntity() != null) {
					r = row(s, rownum);
					cell(r, 0, "Worklogs:");
					rownum++;

					Set<WorklogsEntity> worklogs = entity.getFieldsEntity().getWorklogEntity().getWorklogsEntities();

					Row rAuthor = row(s, rownum);
					rownum++;
					Row rStarted = row(s, rownum);
					rownum++;
					Row rTimeSpentSeconds = row(s, rownum);
					rownum = rownum + 2;
					cell(rAuthor, 0, "Author: ");
					cell(rStarted, 0, "Started: ");
					cell(rTimeSpentSeconds, 0, "TimeSpentSeconds: ");
					cellnum = 1;
					for (WorklogsEntity worklog : worklogs) {
						cellValue = worklog.getUserEntityByIdAuthor().getName();
						cell(rAuthor, cellnum, cellValue);
						cellValue = worklog.getStarted().toString();
						cell(rStarted, cellnum, cellValue);
						cellValue = worklog.getTimeSpentSeconds();
						cell(rTimeSpentSeconds, cellnum, cellValue);
						cellnum++;
					}

				}

				// if (entity.getWatchersEntities() != null) {
				// r = row(s, rownum);
				// cell(r, 0, "Watchers:");
				// rownum++;
				//
				// Set<WatchersEntity> watchers = entity.getWatchersEntities();
				//
				// Row rName = row(s, rownum);
				// rownum++;
				// Row rEmail = row(s, rownum);
				// rownum++;
				// rownum = rownum + 2;
				// cell(rName, 0, "Name: ");
				// cell(rEmail, 0, "EmailAddress: ");
				// cellnum = 1;
				//
				// for (WatchersEntity watcher : watchers) {
				// Set<UserEntity> users = watcher.getUserEntities();
				// for (UserEntity user : users) {
				// cellValue = user.getName();
				// ;
				// cell(rName, cellnum, cellValue);
				// cellValue = user.getEmailAddress();
				// ;
				// cell(rEmail, cellnum, cellValue);
				// cellnum++;
				// }
				//
				// }
				// }

				if (entity.getFieldsEntity().getIssueEntity() == null) {
					if (entity.getSubtasksEntities() != null) {
						r = row(s, rownum);
						cell(r, 0, "Subtasks:");
						rownum++;

						Set<SubtasksEntity> subtasks = entity.getSubtasksEntities();

						Row rKey = row(s, rownum);

						rownum = rownum + 2;
						cell(rKey, 0, "Issue Key: ");
						cellnum = 1;

						for (SubtasksEntity subtask : subtasks) {
							Set<IssueEntity> issues = subtask.getIssueEntities();
							for (IssueEntity issue : issues) {
								cellValue = issue.getKeyIssue();
								cell(rKey, cellnum, cellValue);
								cellnum++;
							}

						}
					}
				}

			}

			/*
			 * r = wb.getSheetAt(0).getRow(0); for (int colNum = 0; colNum <
			 * r.getLastCellNum(); colNum++)
			 * wb.getSheetAt(0).setColumnWidth(colNum, 200);
			 */
			// Save
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(filename);
				wb.write(out);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public void createReportPoiByDeveloper(List<IssueEntity> ticketsList) {

		if (ticketsList.size() != 0) {

			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

			ServletContext ctx = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext());
			String filename = ctx.getRealPath("JSONFolder//outPOI.xls");

			// String filename =
			// classLoader.getResource("JSONFolder//outPOI.xls").getPath();
			Workbook wb = new HSSFWorkbook();

			Sheet s = wb.createSheet();

			Row r = null;
			Cell c = null;
			int rownum = 0;
			String cellValue;

			CellStyle style = wb.createCellStyle();
			style.setFillForegroundColor(IndexedColors.PINK.getIndex());
			style.setFillPattern(CellStyle.SOLID_FOREGROUND);

			UserEntity entityOut = ticketsList.get(0).getFieldsEntity().getUserEntityByIdAuthor();
			String email = entityOut.getEmailAddress();
			String name = entityOut.getName();
			String self = entityOut.getSelf();
			String active = entityOut.getActive();
			long totalTimeSpent = countTotalTimespent(ticketsList);
			int cellnumOut = 0;
			r = row(s, rownum);
			rownum = rownum + 1;
			Cell cellOut = r.createCell(cellnumOut);
			cellOut.setCellValue("Name: " + name);
			cellOut.setCellStyle(style);
			r = row(s, rownum);
			rownum = rownum + 1;
			Cell cellOut1 = r.createCell(cellnumOut);
			cellOut1.setCellValue("Email: " + email);
			cellOut1.setCellStyle(style);
			r = row(s, rownum);
			rownum = rownum + 1;
			Cell cellOut2 = r.createCell(cellnumOut);
			cellOut2.setCellValue("Self: " + self);
			cellOut2.setCellStyle(style);
			r = row(s, rownum);
			rownum = rownum + 1;
			Cell cellOut3 = r.createCell(cellnumOut);
			cellOut3.setCellValue("Active: " + active);
			cellOut3.setCellStyle(style);
			r = row(s, rownum);
			rownum = rownum + 1;
			Cell cellOut4 = r.createCell(cellnumOut);
			cellOut4.setCellValue("Total time spent: " + totalTimeSpent);
			cellOut4.setCellStyle(style);
			rownum = rownum + 2;

			/*
			 * for (int colNum = 0; colNum < r.getLastCellNum(); colNum++) {
			 * wb.getSheetAt(0).autoSizeColumn(colNum); }
			 */
			wb.getSheetAt(0).autoSizeColumn(r.getLastCellNum() - 1);

			for (IssueEntity entity : ticketsList) {
				int cellnum = 0;
				r = row(s, rownum);
				rownum = rownum + 2;

				Cell cell = r.createCell(cellnum);
				cell.setCellValue("Ticket: " + entity.getKeyIssue());
				cell.setCellStyle(style);
				cellnum++;

				cellnum = cell(r, cellnum, entity.getFieldsEntity().getSummary());

				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Reporter: " + entity.getFieldsEntity().getUserEntityByIdReporter().getName());

				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Summary: " + entity.getFieldsEntity().getSummary());
				cellnum = cell(r, cellnum, "Priority: " + entity.getFieldsEntity().getPriorityEntity().getId() + "."
						+ entity.getFieldsEntity().getPriorityEntity().getName());
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "TimeSpent: " + entity.getFieldsEntity().getTimespent());
				cellnum = cell(r, cellnum, "Status: " + entity.getFieldsEntity().getStatusEntity().getId() + "."
						+ entity.getFieldsEntity().getStatusEntity().getName());
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "IssueType: " + entity.getFieldsEntity().getIssueTypeEntity().getId() + "."
						+ entity.getFieldsEntity().getIssueTypeEntity().getName());
				cellnum = cell(r, cellnum, "Description: " + entity.getFieldsEntity().getDescription());
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				if (entity.getFieldsEntity().getIssueEntity() != null) {
					cellnum = cell(r, 1, "Parent Ticket: " + entity.getFieldsEntity().getIssueEntity().getKeyIssue());
				} else {
					cellnum = cell(r, 1, "Parent Ticket: " + "no parent ticket");
				}

				wb.getSheetAt(0).autoSizeColumn(cellnum);

				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Created: " + entity.getFieldsEntity().getCreated());
				cellnum = cell(r, cellnum, "Project: " + entity.getFieldsEntity().getProjectEntity().getName());

				r = row(s, rownum);
				rownum++;
				cellnum = 0;
				cell(r, cellnum, "Updated: " + entity.getFieldsEntity().getUpdated());

				if (entity.getFieldsEntity().getCommentEntity() != null) {

					Set<CommentsEntity> comments = entity.getFieldsEntity().getCommentEntity().getCommentsEntities();
					Row rBody = row(s, rownum);
					rownum++;
					Row rDate = row(s, rownum);
					rownum++;
					Row rAuthor = row(s, rownum);
					rownum = rownum + 2;
					cell(rBody, 0, "Comment Body: ");
					cell(rDate, 0, "Comment created Date: ");
					cell(rAuthor, 0, "Comment Author Name: ");
					cellnum = 1;
					for (CommentsEntity comment : comments) {
						cellValue = comment.getBody();
						cell(rBody, cellnum, cellValue);
						cellValue = comment.getCreated().toString();
						cell(rDate, cellnum, cellValue);
						cellValue = comment.getUserEntityByIdAuthor().getName();
						cell(rAuthor, cellnum, cellValue);
						cellnum++;
					}
					for (int colNum = 0; colNum < rBody.getLastCellNum(); colNum++) {
						wb.getSheetAt(0).autoSizeColumn(colNum);
					}
				}
				if (entity.getFieldsEntity().getResolutionEntity() != null) {
					r = row(s, rownum);
					rownum = rownum + 2;
					cellnum = 0;
					cellnum = cell(r, cellnum, "Resolution: " + entity.getFieldsEntity().getResolutionEntity().getName());
					cellnum = cell(r, cellnum, "Resolution Date: " + entity.getFieldsEntity().getResolutionDate());

					cellnum = cell(r, cellnum, "Descriprion: " + entity.getFieldsEntity().getResolutionEntity().getDescription());
				} else {
					r = row(s, rownum);
					rownum = rownum + 2;
					cellnum = 0;
					cellnum = cell(r, cellnum, "Resolution: no resolution yet");
				}
				r = row(s, rownum);
				rownum = rownum + 2;
				cellnum = 0;
				cellnum = cell(r, cellnum, "Due date: " + entity.getFieldsEntity().getDuedate());

				if (entity.getFieldsEntity().getWorklogEntity() != null) {
					r = row(s, rownum);
					cell(r, 0, "Worklogs:");
					rownum++;

					Set<WorklogsEntity> worklogs = entity.getFieldsEntity().getWorklogEntity().getWorklogsEntities();

					Row rAuthor = row(s, rownum);
					rownum++;
					Row rStarted = row(s, rownum);
					rownum++;
					Row rTimeSpentSeconds = row(s, rownum);
					rownum = rownum + 2;
					cell(rAuthor, 0, "Author: ");
					cell(rStarted, 0, "Started: ");
					cell(rTimeSpentSeconds, 0, "TimeSpentSeconds: ");
					cellnum = 1;
					for (WorklogsEntity worklog : worklogs) {
						cellValue = worklog.getUserEntityByIdAuthor().getName();
						cell(rAuthor, cellnum, cellValue);
						cellValue = worklog.getStarted().toString();
						cell(rStarted, cellnum, cellValue);
						cellValue = worklog.getTimeSpentSeconds();
						cell(rTimeSpentSeconds, cellnum, cellValue);
						cellnum++;
					}

				}

				// if (entity.getWatchersEntities() != null) {
				// r = row(s, rownum);
				// cell(r, 0, "Watchers:");
				// rownum++;
				//
				// Set<WatchersEntity> watchers = entity.getWatchersEntities();
				//
				// Row rName = row(s, rownum);
				// rownum++;
				// Row rEmail = row(s, rownum);
				// rownum++;
				// rownum = rownum + 2;
				// cell(rName, 0, "Name: ");
				// cell(rEmail, 0, "EmailAddress: ");
				// cellnum = 1;
				//
				// for (WatchersEntity watcher : watchers) {
				// Set<UserEntity> users = watcher.getUserEntities();
				// for (UserEntity user : users) {
				// cellValue = user.getName();
				// ;
				// cell(rName, cellnum, cellValue);
				// cellValue = user.getEmailAddress();
				// ;
				// cell(rEmail, cellnum, cellValue);
				// cellnum++;
				// }
				//
				// }
				// }

				if (entity.getFieldsEntity().getIssueEntity() == null) {
					if (entity.getSubtasksEntities() != null) {
						r = row(s, rownum);
						cell(r, 0, "Subtasks:");
						rownum++;

						Set<SubtasksEntity> subtasks = entity.getSubtasksEntities();

						Row rKey = row(s, rownum);

						rownum = rownum + 2;
						cell(rKey, 0, "Issue Key: ");
						cellnum = 1;

						for (SubtasksEntity subtask : subtasks) {
							Set<IssueEntity> issues = subtask.getIssueEntities();
							for (IssueEntity issue : issues) {
								cellValue = issue.getKeyIssue();
								cell(rKey, cellnum, cellValue);
								cellnum++;
							}

						}
					}
				}

			}

			/*
			 * r = wb.getSheetAt(0).getRow(0); for (int colNum = 0; colNum <
			 * r.getLastCellNum(); colNum++)
			 * wb.getSheetAt(0).setColumnWidth(colNum, 200);
			 */
			// Save
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(filename);
				wb.write(out);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public Row row(Sheet sheet, int rowIndex) {
		Row r = sheet.createRow(rowIndex);
		return r;

	}

	public int cell(Row row, int cellIndex, String value) {
		Cell cell = row.createCell(cellIndex);
		cell.setCellValue(value);
		return ++cellIndex;

	}

	public void createReport(List<IssueEntity> ticketsList) {

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		Map<String, List<IssueEntity>> map = new HashMap<String, List<IssueEntity>>();
		map.put("entity", ticketsList);

		ServletContext ctx = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext());

		XLSTransformer transformer = new XLSTransformer();
		try {
			transformer.transformXLS(classLoader.getResource("JSONFolder//template.xls").getPath(), map, ctx.getRealPath("JSONFolder//outPOI.xls"));
		} catch (ParsePropertyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void createReportTest(List<IssueEntity> ticketsList) {

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		Map<String, List<IssueEntity>> map = new HashMap<String, List<IssueEntity>>();
		map.put("entity", ticketsList);

		XLSTransformer transformer = new XLSTransformer();
		try {
			transformer.transformXLS(classLoader.getResource("JSONFolder//template.xls").getPath(), map,
					classLoader.getResource("JSONFolder//outPOI.xls").getPath());

			System.out.println(classLoader.getResource("JSONFolder//outPOI.xls").getPath());
		} catch (ParsePropertyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public TreeNode createReducedIssueTreeTable(TreeNode parentNode, List<IssueEntity> issues) {
		TreeNode issueNode;

		TreeNode issuesRoot = new DefaultTreeNode(new Document("Issues", "-"), parentNode);
		issuesRoot.setExpanded(true);
		for (IssueEntity issue : issues) {
			System.out.println(issue);
			FieldsEntity fields = issue.getFieldsEntity();
			UserEntity reporter = fields.getUserEntityByIdReporter();
			StatusEntity status = fields.getStatusEntity();
			IssueTypeEntity issueType = fields.getIssueTypeEntity();
			ProjectEntity project = fields.getProjectEntity();
			WorklogEntity worklog = fields.getWorklogEntity();
			if (issue.getFieldsEntity().getTimespent() != null) {
				issueNode = createTreeNode(issue.getKeyIssue(), getTimeDuration(issue.getFieldsEntity().getTimespent()), issuesRoot);
			} else {
				issueNode = createTreeNode(issue.getKeyIssue(), "-", issuesRoot);
			}
			if (fields.getDuedate() == null) {
				createTreeNode("Duedate", "no duedate", issueNode);
			} else {
				createTreeNode("Duedate ", fields.getDuedate().toString(), issueNode);
			}

			// Basic TreeNode for some misc
			TreeNode general = createTreeNode("GeneralInfo", "-", issueNode);

			if (reporter == null) {
				createTreeNode("Reporter(Name / Email)", "Issue has no reporter", general);
			} else {
				createTreeNode("Reporter(Name / Email)", reporter.getName() + " / " + reporter.getEmailAddress(), general);
			}

			createTreeNode("Summary", fields.getSummary(), general);

			createTreeNode("Timespent", String.valueOf(fields.getTimespent()), general);

			if (status == null) {
				createTreeNode("Status", "Issue has no status", issueNode);
			} else {
				createTreeNode("Status", status.getName(), issueNode);
			}

			if (issueType == null) {
				createTreeNode("IssueType", "Issue has no type", issueNode);
			} else {
				createTreeNode("IssueType", issueType.getName(), issueNode);
			}

			if (project == null) {
				createTreeNode("Project", "Issue has no project", general);
			} else {
				createTreeNode("Project", project.getKeyProject(), general);
			}

			if (fields.getCreated() == null) {
				createTreeNode("Updated", "Issue status not changed yet", general);
			}
			if (fields.getCreated() != null) {
				createTreeNode("Created", fields.getCreated().toString(), general);
			}

			if (worklog != null) {
				// Basic TreeNode for worklog
				TreeNode worklogNode = createTreeNode("Worklog", "-", issueNode);
				Set<WorklogsEntity> worklogs = worklog.getWorklogsEntities();
				int i = 0;
				for (WorklogsEntity work : worklogs) {
					i++;
					// Basic TreeNode for single worklog
					TreeNode singleWorklogNode = createTreeNode("Worklog" + i, "", worklogNode);
					createTreeNode("Author", work.getUserEntityByIdAuthor().getName(), singleWorklogNode);
					createTreeNode("Started", work.getStarted().toString(), singleWorklogNode);
					createTreeNode("Updated", work.getUpdated().toString(), singleWorklogNode);
					createTreeNode("TimeSpent", work.getTimeSpentSeconds(), singleWorklogNode);

				}

			}

			general.setExpanded(true);
		}

		return issuesRoot;
	}

	public TreeNode createIssueTreeTable(TreeNode parentNode, List<IssueEntity> list) {
		TreeNode issueNode;
		// root = new DefaultTreeNode("root", null);

		TreeNode issues = new DefaultTreeNode(new Document("Issues", "-"), parentNode);
		issues.setExpanded(true);
		for (IssueEntity issue : list) {
			System.out.println(issue);
			// Set<WatchersEntity> watchers = issue.getWatchersEntities();
			Set<SubtasksEntity> subtasks = issue.getSubtasksEntities();
			FieldsEntity fields = issue.getFieldsEntity();
			UserEntity reporter = fields.getUserEntityByIdReporter();
			UserEntity assignee = fields.getUserEntityByIdAuthor();
			PriorityEntity priority = fields.getPriorityEntity();
			StatusEntity status = fields.getStatusEntity();
			IssueTypeEntity issueType = fields.getIssueTypeEntity();
			ProjectEntity project = fields.getProjectEntity();
			ResolutionEntity resolution = fields.getResolutionEntity();
			CommentEntity comment = fields.getCommentEntity();
			IssueEntity parentIssue = fields.getIssueEntity();
			WorklogEntity worklog = fields.getWorklogEntity();

			// Basic TreeNode for issue
			if (fields.getDuedate() == null) {
				issueNode = createTreeNode(issue.getKeyIssue(), "no duedate", issues);
			} else {
				issueNode = createTreeNode(issue.getKeyIssue(), "Duedate " + fields.getDuedate().toString(), issues);
			}
			// Basic TreeNode for some misc
			TreeNode general = createTreeNode("GeneralInfo", "-", issueNode);

			if (reporter == null) {
				createTreeNode("Reporter(Name / Email)", "Issue has no reporter", general);
			} else {
				createTreeNode("Reporter(Name / Email)", reporter.getName() + " / " + reporter.getEmailAddress(), general);
			}
			if (assignee == null) {
				createTreeNode("Assignee(Name / Email)", "Issue has no assignee", general);
			} else {
				createTreeNode("Assignee(Name / Email)", assignee.getName() + " / " + assignee.getEmailAddress(), general);
			}
			createTreeNode("Summary", fields.getSummary(), general);

			createTreeNode("Description", fields.getDescription(), general);
			createTreeNode("Timespent", String.valueOf(fields.getTimespent()), general);
			if (priority == null) {
				createTreeNode("Priority", "Issue has no Priority", general);
			} else {
				createTreeNode("Priority", priority.getName(), general);
			}
			if (status == null) {
				createTreeNode("Status", "Issue has no status", issueNode);
			} else {
				createTreeNode("Status", status.getName(), issueNode);
			}
			if (issueType == null) {
				createTreeNode("IssueType", "Issue has no type", issueNode);
			} else {
				createTreeNode("IssueType", issueType.getName(), issueNode);
			}
			if (project == null) {
				createTreeNode("Project", "Issue has no project", general);
			} else {
				createTreeNode("Project", project.getKeyProject(), general);
			}
			if (fields.getCreated() == null) {
				createTreeNode("Updated", "Issue status not changed yet", general);
			}
			if (fields.getCreated() != null) {
				createTreeNode("Created", fields.getCreated().toString(), general);
			}
			if (resolution != null) {
				createTreeNode("Resolution", resolution.getDescription(), issueNode);
			}
			// Basic TreeNode for subtasks
			TreeNode subtask = createTreeNode("Subtasks", "-", issueNode);

			if (parentIssue == null) {
				if (subtasks != null) {
					System.out.println(subtasks);
					for (SubtasksEntity sub : subtasks) {
						Set<IssueEntity> issuesSet = sub.getIssueEntities();
						for (IssueEntity issueSubtask : issuesSet) {
							createTreeNode(issueSubtask.getKeyIssue(), issueSubtask.getSelf(), subtask);
						}

					}
				}

			}

			if (parentIssue != null) {
				createTreeNode("Parent issue", parentIssue.getKeyIssue(), issueNode);
			}

			if (comment != null) {
				// Basic TreeNode for comments
				TreeNode commentsNode = createTreeNode("Comments", "-", issueNode);
				Set<CommentsEntity> comments = comment.getCommentsEntities();
				int i = 0;
				for (CommentsEntity comm : comments) {
					i++;
					TreeNode commentNode = createTreeNode("Comment" + i, "-", commentsNode);
					createTreeNode("Author / UpdateAuthor", comm.getUserEntityByIdAuthor().getName() + " / "
							+ comm.getUserEntityByIdUpdateAuthor().getName(), commentNode);
					createTreeNode("Created Date / Updated Date", comm.getCreated().toString() + " / " + comm.getUpdated().toString(), commentNode);

					createTreeNode("Data", comm.getBody(), commentNode);

				}
			}
			if (worklog != null) {
				// Basic TreeNode for worklog
				TreeNode worklogNode = createTreeNode("Worklog", "-", issueNode);
				Set<WorklogsEntity> worklogs = worklog.getWorklogsEntities();
				int i = 0;
				for (WorklogsEntity work : worklogs) {
					i++;
					// Basic TreeNode for single worklog
					TreeNode singleWorklogNode = createTreeNode("Worklog" + i, "", worklogNode);
					createTreeNode("Author", work.getUserEntityByIdAuthor().getName(), singleWorklogNode);
					createTreeNode("Started", work.getStarted().toString(), singleWorklogNode);
					createTreeNode("Updated", work.getUpdated().toString(), singleWorklogNode);
					createTreeNode("TimeSpent", work.getTimeSpentSeconds(), singleWorklogNode);

				}

			}

			// if (watchers != null) {
			// // Basic TreeNode for watchers
			// TreeNode watchersNode = createTreeNode("Watchers", "-",
			// issueNode);
			// for (WatchersEntity watc : watchers) {
			// Set<UserEntity> watchersUser = watc.getUserEntities();
			// for (UserEntity user : watchersUser) {
			// createTreeNode("Watcher(Name / Email)", user.getName() + " / " +
			// user.getEmailAddress(), watchersNode);
			// }
			// }
			// }
			subtask.setExpanded(true);
			general.setExpanded(true);
		}

		return issues;

	}

	public TreeNode createTreeNode(String str1, String str2, TreeNode parent) {
		return new DefaultTreeNode(new Document(str1, str2), parent);

	}

	public long countTotalTimespent(List<IssueEntity> issues) {
		long totalTimespent = 0L;
		for (IssueEntity issue : issues) {
			if (issue.getFieldsEntity().getTimespent() != null) {
				totalTimespent += issue.getFieldsEntity().getTimespent();
			}
		}
		return totalTimespent;
	}

	public String getTimeDuration(long time) {
		if (time == 0) {
			return "-";
		} else {
			StringBuilder sb = new StringBuilder();
			sb.append(time / 3600);
			sb.append("hours ");
			sb.append((time % 3600) / 60);
			sb.append("minutes");
			return sb.toString();
		}
	}
}
